/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> result;
        preorder(root, result);
        return result;
    }

    void preorder(TreeNode *node, vector<int> &result) {
        if (!node) return;
        result.emplace_back(node->val);
        preorder(node->left, result);
        preorder(node->right, result);
    }
};

class Solution2 {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode *> stk;
        if (root) stk.push(root);
        while (!stk.empty()) {
            TreeNode *node = stk.top(); stk.pop();
            if (node) {
                if (node->right) stk.push(node->right);
                if (node->left) stk.push(node->left);
                stk.push(node);
                stk.push(nullptr);
            } else {
                node = stk.top(); stk.pop();
                result.emplace_back(node->val);
            }
        }
        return result;
    }
};

class Solution3 {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode *> stk;
        if (!root) return result;
        stk.push(root);
        while (!stk.empty()) {
            TreeNode *node = stk.top(); stk.pop();
            result.emplace_back(node->val);
            if (node->right) stk.push(node->right);
            if (node->left) stk.push(node->left);
        }
        return result;
    }
};